package com.permission_demo.handler;

import com.permission_demo.annotation.Permission;
import lombok.Data;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class PermissionBeanPostProcessor implements BeanPostProcessor {

    public static final List<PermissionBean> PERMISSION_BEANS = new ArrayList<>();

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!AopUtils.isAopProxy(bean)) { // 检查bean是否为AOP代理
            return bean;
        }
        Class<?> target = AopProxyUtils.ultimateTargetClass(bean); // 获取最终的目标类对象
        System.out.println("Target class: " + target.getName());
        Permission classPermission = target.getAnnotation(Permission.class);
        if (Objects.isNull(classPermission)) {
            return bean;
        }
        System.out.println(classPermission);
        String rootUrl = getRootUrl(target);
        for (Method method : target.getDeclaredMethods()) {
            Permission methodPermission = method.getAnnotation(Permission.class);
            if (Objects.isNull(methodPermission)) {
                continue;
            }
            PermissionBean permissionBean = new PermissionBean();
            permissionBean.setCCode(classPermission.code());
            permissionBean.setCDesc(classPermission.desc());
            permissionBean.setPCode(methodPermission.code());
            permissionBean.setPDesc(methodPermission.desc());
            permissionBean.setUrl(rootUrl + getMethodUrl(method));
            PERMISSION_BEANS.add(permissionBean);
        }
        System.out.println(PERMISSION_BEANS);
        return bean;
    }

    private String getRootUrl(Class<?> target) {
        // Controller 类上可能是其他注解，此次没补全
        RequestMapping requestMapping = target.getAnnotation(RequestMapping.class);
        if (Objects.isNull(requestMapping) || requestMapping.value().length < 1) {
            return null;
        }
        return requestMapping.value()[0];
    }

    private String getMethodUrl(Method method) {
        // 方法上可能是其他注解，此次没补全
        GetMapping getMapping = method.getAnnotation(GetMapping.class);
        if (Objects.isNull(getMapping) || getMapping.value().length < 1) {
            return null;
        }
        return getMapping.value()[0];
    }

    @Data
    public static class PermissionBean {
        private String cCode;
        private String cDesc;
        private String pCode;
        private String pDesc;
        private String url;
    }
}
